package com.example.presentation_libary.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import androidx.annotation.Nullable;

import com.example.presentation_libary.presentation.MultiScreenPresentation;


/**
 * 控制副屏显示 的服务
 */
public class MultiScreenService extends Service {
    private static final String TAG = "MultiScreenService";
    /**
     * 屏幕管理器
     */
    private DisplayManager mDisplayManager;

    /**
     * 屏幕数组
     */
    private Display[] displays;


    /**
     * 辅屏
     */
    private MultiScreenPresentation presentation;

    public MultiScreenPresentation getPresentation() {
        return presentation;
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MultiScreenBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "=启动了副屏显示服务==");
        initPresentation();
    }


    private void initPresentation() {
        if (presentation == null) {
            mDisplayManager = (DisplayManager) this.getSystemService(Context.DISPLAY_SERVICE);
            displays = mDisplayManager.getDisplays();//得到显示器数组
            Log.i(TAG, "= displays 的数量 ==" + displays.length);
            if (displays.length > 1) {
                presentation = new MultiScreenPresentation(this.getApplicationContext(), displays[1]);
                presentation.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            }
        }
    }

    /**
     * 显示第二块屏
     */
    public void showSecondPresentation() {
        Log.i(TAG, "= 开始副屏显示 ==");
        if (presentation != null) {
            presentation.show();
        }
    }

    /**
     * 关闭第二块屏
     */
    public void dimssSecondPresentation() {
        Log.i(TAG, "= 开始关闭副屏显示 ==");
        if (presentation != null) {
            presentation.dismiss();
        }
    }

    //内部 Binder类  实现服务的对象的实例
    public class MultiScreenBinder extends Binder {
        public MultiScreenService getService() {
            return MultiScreenService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dimssSecondPresentation();
        if (presentation != null) {
            presentation = null;
        }
        stopSelf();
    }
}
